﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using PersistentManager.Query.Sql;
using System.Data.Common;
using PersistentManager.Query;
using PersistentManager.GAC;

namespace PersistentManager.Provider
{
    internal class SQLLiteDatabaseProvider : DatabaseProvider
    {
        internal SQLLiteDatabaseProvider( IDbConnection connection , IDbTransaction transaction )
            : base( connection , transaction )
		{

		}

        public override DbDataReader Range( SQLTokenizer tokens , int StartRange , int Endrange , string query , List<DbParameter> parameters )
        {
            query = string.Concat( query , string.Format( " LIMIT {0}, {1}" , StartRange , Endrange - StartRange ) );

            return GetDataReader( query , parameters );
        }

        public override SQLTokenizer GetFilteredQuerySyntax( SQLTokenizer Tokens , int index )
        {
            Tokens.AddFormatted( QueryPart.Appender , string.Format( " LIMIT {0} " , index ) );

            return Tokens;
        }

        public override int ExecuteUpdate( string query , ref DbParameter returnedValue , string columnName , List<DbParameter> parameters )
        {
            int update = ExecuteUpdate( query , parameters );
            returnedValue.Value = GetAutoGeneratedColumnValue( );

            return update;
        }

        public override string GetNamingStrategyString( )
        {
            return "[{0}]";
        }

        public override string GetParameterPrefix( )
        {
            return "@";
        }

        public object GetAutoGeneratedColumnValue( )
        {
            return ExecuteScalar( "select last_insert_rowid()" );
        }

        public override bool SupportsMultipleActiveReader
        {
            get
            {
                return false;
            }
        }

        public override DbParameter GetCommandParameter( string name , object value )
        {
            return ( DbParameter )GacLoader.GetParameter( new Guid( EmbeddedProviderGUID.SQLLite_GUID ) , name , value , false );
        }
    }
}
